﻿// ============================================================================
//  _ __   ___  ___  ___ _ __ ___  _   _
// | '_ \ / _ \/ __|/ _ \ '_ ` _ \| | | |
// | | | |  __/\__ \  __/ | | | | | |_| |
// |_| |_|\___||___/\___|_| |_| |_|\__,_|
//
// NES Emulator by daxnet, 2024
// MIT License
// ============================================================================

using System.Reflection;
using System.Windows.Controls;
using System.Xml;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;

namespace NesEmu.Explorer.Controls;

/// <summary>
///     Interaction logic for NesCodeEditor.xaml
/// </summary>
public partial class NesCodeEditor : UserControl
{
    #region Private Fields

    private string? _syntaxHighlightingDefinitionResourceName;

    #endregion Private Fields

    #region Public Constructors

    public NesCodeEditor()
    {
        InitializeComponent();
        codeEditor.Text = "public string _text;";
    }

    #endregion Public Constructors

    #region Public Properties

    public bool IsReadOnly
    {
        get => codeEditor.IsReadOnly;
        set => codeEditor.IsReadOnly = value;
    }

    public string? SyntaxHighlightingDefinitionResourceName
    {
        get => _syntaxHighlightingDefinitionResourceName;
        set
        {
            if (!string.IsNullOrEmpty(value) && !string.Equals(_syntaxHighlightingDefinitionResourceName, value))
            {
                _syntaxHighlightingDefinitionResourceName = value;
                using var stream = Assembly.GetAssembly(GetType())?.GetManifestResourceStream(value);
                if (stream != null)
                {
                    using var xmlReader = XmlReader.Create(stream);
                    codeEditor.SyntaxHighlighting = HighlightingLoader.Load(xmlReader, HighlightingManager.Instance);
                }
            }
        }
    }

    public string Text
    {
        get => codeEditor.Text;
        set => codeEditor.Text = value;
    }

    #endregion Public Properties
}